<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="500px" :title="`新增库房`">
    <p></p>
    <el-form ref="ruleFormRef" label-width="150px" label-suffix=" :" :rules="rules" :model="warehouseInfo">
      <el-form-item label="库房名" prop="warehouseName">
        <el-input v-model="warehouseInfo!.warehouseName" placeholder="请填写客户姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="库房地址（省）" prop="warehouseAddress.province">
        <el-select v-model="warehouseInfo!.warehouseAddress!.province" placeholder="请选择省份" @change="onProvinceChange">
          <el-option v-for="province in provinceList" :key="province" :label="province" :value="province"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="库房地址（市）" prop="warehouseAddress.city">
        <el-select v-model="warehouseInfo!.warehouseAddress!.city" placeholder="请选择城市" @change="onCityChange">
          <el-option v-for="city in cityList" :key="city" :label="city" :value="city"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="库房地址（区）" prop="warehouseAddress.zone">
        <el-select v-model="warehouseInfo!.warehouseAddress!.zone" placeholder="请选择区县">
          <el-option v-for="district in districtList" :key="district" :label="district" :value="district"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" prop="warehouseAddress.detail">
        <el-input v-model="warehouseInfo!.warehouseAddress!.detail" placeholder="请填写客户详细地址" clearable></el-input>
      </el-form-item>
      <el-form-item label="库房等级" prop="warehouseLevel">
        <el-select v-model="warehouseInfo!.warehouseLevel" placeholder="请选择库房等级" clearable>
          <el-option label="中心库房" value="0"></el-option>
          <el-option label="分站库房" value="1"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="tsx" name="UserDrawer">
import { ref, reactive, onMounted } from "vue";
import { FormInstance } from "element-plus";
import { addWarehouse } from "@/api/modules/warehouse";
import axios from "axios";
//import { provinceAndCityData, regionData, provinceAndCityDataPlus, regionDataPlus, CodeToText, TextToCode } from 'element-china-area-data'

const rules = reactive({
  warehouseName: [{ required: true, message: "请填写客户姓名" }],
  "warehouseAddress.province": [{ required: true, message: "请填写省份" }],
  "warehouseAddress.city": [{ required: true, message: "请填写城市" }],
  "warehouseAddress.zone": [{ required: true, message: "请填写地区" }],
  "warehouseAddress.detail": [{ required: true, message: "请填写详细地址" }],
  warehouseLevel: [{ required: true, message: "请填写库房等级" }]
});

const initialDate = new Date();

interface DrawerProps {
  title?: string;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerProps = ref<DrawerProps>({
  title: "新增客户"
});
const drawerVisible = ref(false);

const warehouseInfo = ref<Partial<any>>({
  warehouseId: 0,
  warehouseName: "",
  warehouseAddress: {
    province: "",
    city: "",
    zone: "",
    detail: ""
  },
  warehouseLevel: undefined,
  createTime: initialDate,
  deleted: 0
});

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await addWarehouse(warehouseInfo.value);
      drawerVisible.value = false;
      drawerProps.value.getTableList!();
    } catch (error) {
      console.log(error);
    }
  });
};

const provinceList = ref([]);
const cityList = ref([]);
const districtList = ref([]);

const fetchProvinces = async () => {
  try {
    const response = await axios.get(
      "https://restapi.amap.com/v3/config/district?keywords=中国&subdistrict=1&key=7d36a7cce58b0b66bb018cc58cf3498f"
    );
    const provinces = response.data?.districts[0]?.districts || [];
    provinceList.value = provinces.map((province: any) => province.name);
  } catch (error) {
    console.error(error);
  }
};

const fetchCities = async (province: string) => {
  try {
    const response = await axios.get(
      `https://restapi.amap.com/v3/config/district?keywords=${province}&subdistrict=1&key=7d36a7cce58b0b66bb018cc58cf3498f`
    );
    const cities = response.data?.districts[0]?.districts || [];
    cityList.value = cities.map((city: any) => city.name);
  } catch (error) {
    console.error(error);
  }
};

const fetchDistricts = async (city: string) => {
  try {
    const response = await axios.get(
      `https://restapi.amap.com/v3/config/district?keywords=${city}&subdistrict=1&key=7d36a7cce58b0b66bb018cc58cf3498f`
    );
    const districts = response.data?.districts[0]?.districts || [];
    districtList.value = districts.map((district: any) => district.name);
  } catch (error) {
    console.error(error);
  }
};

const onProvinceChange = (province: string) => {
  warehouseInfo!.value.warehouseAddress!.city = "";
  warehouseInfo!.value.warehouseAddress!.zone = "";
  fetchCities(province);
};

const onCityChange = (city: string) => {
  warehouseInfo!.value.warehouseAddress!.zone = "";
  fetchDistricts(city);
};

onMounted(() => {
  fetchProvinces();
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

defineExpose({
  acceptParams
});
</script>
